package com.sinosig.slbi.gm;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * @ClassName: SM4Util
 */
public class SM4Util {

    public static final String ALGORITHM_NAME = "SM4";
    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
    public static final String ALGORITHM_NAME_CBC_PADDING = "SM4/CBC/PKCS7Padding";

    /**
     * sm4解密
     */
    public static byte[] sm4Decrypt(byte[] sm4Key, byte[] ciphertext, String algorithm) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithm, BouncyCastleProvider.PROVIDER_NAME);
        Key key = new SecretKeySpec(sm4Key, ALGORITHM_NAME);
        if (ALGORITHM_NAME_ECB_PADDING.equals(algorithm)) {
            cipher.init(Cipher.DECRYPT_MODE, key);
        } else if (ALGORITHM_NAME_CBC_PADDING.equals(algorithm)){
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(new byte[16]));
        }
        return cipher.doFinal(ciphertext);
    }

    /**
     * sm4加密
     */
    public static byte[] sm4Encrypt(byte[] sm4Key, String src, String algorithm) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithm, BouncyCastleProvider.PROVIDER_NAME);
        Key key = new SecretKeySpec(sm4Key, ALGORITHM_NAME);
        if (ALGORITHM_NAME_ECB_PADDING.equals(algorithm)) {
            cipher.init(Cipher.ENCRYPT_MODE, key);
        } else if (ALGORITHM_NAME_CBC_PADDING.equals(algorithm)){
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(new byte[16]));
        }
        return cipher.doFinal(src.getBytes(StandardCharsets.UTF_8));
    }
    public enum SM4ALGORITHM{
        ALGORITHM_NAME_ECB_PADDING,ALGORITHM_NAME_CBC_PADDING
    }
}
